package net.oschina.arvin.dbjava.type;

import net.oschina.arvin.dbjava.model.Column;

/**
 * <pre>
 *     参考地址： https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-type-conversions.html
 *
 *     以下情况会被认为是Boolean类型：
 *     1. MysqlType = BOOL, BOOLEAN
 *     2. BIT(1)
 *     3. TINYINT(1)  如果toBoolForLenOneNumber = false，则不认为是Boolean类型
 * </pre>
 *
 * @author Arvin
 * @time 2017/9/29 9:41
 */
public class BooleanDBJavaTypeConverter implements DBJavaTypeConverter {

    @Override
    public Class<?> convertToJavaType(Column column, boolean toBoolForLenOneNumber, boolean useUtilDate, boolean wrapMode) {
        String dataType = column.getDataType().toUpperCase();
        boolean isBooleanType = false;
        if ("BOOL".equals(dataType) || "BOOLEAN".equals(dataType)) {
            isBooleanType = true;
        } else if ("BIT".equals(dataType) && (null == column.getColumnLen() || column.getColumnLen() < 2) && toBoolForLenOneNumber) {
            isBooleanType = true;
        } else if ("TINYINT".equals(dataType) && (null == column.getColumnLen() || column.getColumnLen() < 2) && toBoolForLenOneNumber) {
            isBooleanType = true;
        }
        if (isBooleanType) {
            return wrapMode ? Boolean.class : boolean.class;
        }
        return null;
    }

    @Override
    public String convertToDBColumnType(Class<?> javaType) {
        if (javaType == boolean.class || javaType == Boolean.class) {
            return "TINYINT(1)";
        }
        return null;
    }
}
